//
//  HBNovelDetailController.m
//  HeartBeat
//
//  Created by karong on 2023/8/28.
//

#import "HBNovelDetailController.h"
#import "HBNovelInfoCell.h"
#import "HBNovelScoreCell.h"
#import "HBNovelVipCell.h"
#import "HBNovelIntroCell.h"
#import "HBNovelMenuCell.h"
@interface HBNovelDetailController () <HBNovelIntroCellDelegate, HBNovelScoreCellDelegate, HBNovelMenuCellDelegate, HBNovelVipCellDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (weak, nonatomic) IBOutlet UIButton *readBtn;
@property (weak, nonatomic) IBOutlet UIButton *followBtn;
@property (nonatomic, assign) BOOL showFullDesc;
@property (nonatomic, assign) BOOL needReload;
@end

@implementation HBNovelDetailController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.needReload) {
        self.needReload = NO;
        [self refreshData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self addObserver];
    [self layoutFollow];
    [self layoutBgColor];
    [self refreshData];
    [HBEvenManager event:@"shelf_add" evenLogType:(HBEvenLogType_Pop)
              attributes:@{@"type_selection":@"3"}];
}

- (void)addObserver {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(needReloadData) name:HBRefreshChapterNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(needReloadData) name:HBRefreshBookInfoNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(needReloadData) name:HBRefreshFollowNotification object:nil];
    
}

- (void)needReloadData {
    self.needReload = YES;
}

- (void)layoutMainView {
    
}

- (void)layoutFollow {
    [self.followBtn setTitle:self.novel.is_bookshelf?WSLocalized(@"已在追書"):WSLocalized(@"加入追書")forState:(UIControlStateNormal)];
    self.followBtn.selected = self.novel.is_bookshelf;
    [self.followBtn setButtonImageTitleStyle:(WSButtonImageTitleStyleTop) padding:5.5];
}

- (void)layoutBgColor {
        if (self.novel.thumb && !self.novel.mostColor) {
            UIImageView * image = [UIImageView new];
            [image sd_setImageWithURL:[NSURL URLWithString:self.novel.thumb] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if (image) {
                    self.novel.mostColor = [HBTool mostColor:image];
                    [self layoutBgColor];
                }
            }];
        }
        else {
            if (![HBTool isLighterColor:self.novel.mostColor]) {
                UIButton * btn = [self.view viewWithTag:1002];
                [btn setImage:IMG(@"icon_back_w") forState:(UIControlStateNormal)];
            }
        }
}

- (void)refreshData {
    WeakSelf
    [HBRequest loadNovelDetailWithId:self.novel.book_id success:^(id obj) {
        if (obj) {
            weakSelf.novel = obj;
            [weakSelf layoutBgColor];
            [weakSelf layoutFollow];
            [weakSelf.listView reloadData];
        }
        else {
            [HBToast simple:WSLocalized(@"書籍遇到了不可抗力，找不到了")];
            [weakSelf popVC];
        }
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        [weakSelf popVC];
    }];
}

- (void)followRequest {
    WeakSelf
    [HBRequest addBookshelfWithAddArray:@[self.novel] success:^{
        weakSelf.novel.is_bookshelf = YES;
        [weakSelf layoutFollow];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)unfollowRequest {
    WeakSelf
    [HBRequest delBookshelfWithDelArray:@[self.novel] success:^{
        weakSelf.novel.is_bookshelf = NO;
        [weakSelf layoutFollow];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

///跳转閱讀器
- (void)showReaderView:(HBChapterModel *)chapter {
    [ViewManager pushReadVCWithNovel_id:self.novel.book_id chapter_id:chapter?chapter.id:self.novel.chapter_id inController:self];
}

- (IBAction)readAction:(id)sender {
    [self showReaderView:nil];
}

- (IBAction)followAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self followRequest];
        [HBEvenManager event:@"shelf_add" evenLogType:(HBEvenLogType_Click)
                  attributes:@{@"type_selection":@"3"}];
    }
    else {
        [self unfollowRequest];
    }
}


#pragma mark UICollectionDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    if (!self.novel) {
        return 0;
    }
    return 5;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger count = 1;
    if (section == 2) {
        if (self.novel.is_vip && appUserCenter.vip_status != 1) {
        }
        else {
            count = 0;
        }
    }
    return count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell * cell;
    if (indexPath.section == 0) {
        HBNovelInfoCell * novelInfoCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HBNovelInfoCell" forIndexPath:indexPath];
        [novelInfoCell setDataWithObject:self.novel];
        cell = novelInfoCell;
    }
    else if (indexPath.section == 1) {
        HBNovelScoreCell * novelScoreCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HBNovelScoreCell" forIndexPath:indexPath];
        novelScoreCell.delegate = self;
        [novelScoreCell setDataWithObject:self.novel];
        cell = novelScoreCell;
    }
    else if (indexPath.section == 2) {
        HBNovelVipCell * novelVipCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HBNovelVipCell" forIndexPath:indexPath];
        novelVipCell.delegate = self;
        [novelVipCell setDataWithObject:self.novel];
        cell = novelVipCell;
    }
    else if (indexPath.section == 3) {
        HBNovelIntroCell * novelIntroCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HBNovelIntroCell" forIndexPath:indexPath];
        novelIntroCell.delegate = self;
        [novelIntroCell setDataWithObject:self.novel];
        cell = novelIntroCell;
    }
    else if (indexPath.section == 4) {
        HBNovelMenuCell * novelMenuCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HBNovelMenuCell" forIndexPath:indexPath];
        novelMenuCell.delegate = self;
        [novelMenuCell setDataWithObject:self.novel];
        cell = novelMenuCell;
    }
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeZero;
    size.width = HBScreenWidth;
    if (indexPath.section == 0) {
        size.height = 25 + 121 + 74 + 20 + 26 + HBStatusBarHeight;
    }
    else if (indexPath.section == 1) {
        size.height = 25 + 45;
    }
    else if (indexPath.section == 2) {
        size.height = 51 + 19;
    }
    else if (indexPath.section == 3) {
        CGFloat descHeight = [self.novel.desc boundingRectWithSize:CGSizeMake(HBScreenWidth - 12 - 12, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]} context:nil].size.height;
        if (descHeight < 51) {
            size.height = ceil(descHeight) + 51 + 57;
        }
        else {
            size.height = self.showFullDesc ? ceil(descHeight + 51 + 57) : 51 + 51 + 57;
        }
    }
    else if (indexPath.section == 4) {
        size.height = 55;
    }
    return size;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    UIEdgeInsets inset = UIEdgeInsetsZero;
    //    inset.bottom = 20;
    //    if (section == 2) {
    //        if (self.novel.is_vip && appUserCenter.vip_status != 1) {
    //        }
    //        else {
    //            inset.bottom = 0;
    //        }
    //    }
    return inset;
}
#pragma mark HBNovelScoreCellDelegate
- (void)novelScoreCellScoreAction {
    if (self.novel.is_score == 0) {
        [ViewManager pushScoreVCWithNovel:self.novel inController:self];
    }
    else {
        [HBToast simple:WSLocalized(@"你已經評過分啦~")];
    }
}
#pragma mark HBNovelVipCellDelegate
- (void)novelVipCellAction {
    HBChapterModel * chapter = [HBChapterModel new];
    chapter.book_id = self.novel.book_id;
    [ViewManager pushMembershipVCWithChapter:chapter inController:self];
}

#pragma mark HBNovelIntroCellDelegate
- (void)novelIntroCellOpenFullDesc {
    self.showFullDesc = !self.showFullDesc;
    [self.listView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:3]]];
}

#pragma mark HBNovelMenuCellDelegate
- (void)novelMenuCellMoreAction {
    [ViewManager showChapterVCWithNovel:self.novel selectHandle:^(id obj) {
        [self showReaderView:obj];
    } inController:self];
}

@end
